(function() {
    'use strict';

    angular
        .module('milkbeeApp')
        .controller('PubCardDialogController', PubCardDialogController);
    PubCardDialogController.$inject = ['$timeout', '$scope', '$http','$stateParams', '$uibModalInstance','AlertService', 'entity', 'Card'];

    function PubCardDialogController ($timeout, $scope, $http,$stateParams, $uibModalInstance,AlertService, entity, Card) {
        var vm = this;

        vm.card = entity;
        vm.card.cost=0;
        vm.clear = clear;
        vm.datePickerOpenStatus = {};
        vm.openCalendar = openCalendar;
        vm.save = save;
        vm.ue=null;
        vm.cannotpost=false;
        vm.currentProcess=0;
        vm.doUpload=false;
        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        	vm.ue = UM.getEditor('myeditor',{       		
                    imageUrl: '/upload/picture',
                    imagePath:'/content/images/upload/picture/',
                    imageFieldName:'jyfile',
                    imageMaxSize: 9216,
                    initialFrameHeight:200,
                    imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
                    focus: true
                    
        	});
        	
        	vm.ue.addListener( "selectionchange", function () {
        		vm.card.content=vm.ue.getContent();
            });
        });

        function clear () {
        	vm.ue.destroy();
        	//document.getElementById('xxxxx').innerHTML='';	
            $uibModalInstance.dismiss('cancel');    
        }

        function save () {
        	//vm.ue.destroy();
        	//alert(vm.ue.getContent());
        	vm.card.content=vm.ue.getContent();
        	if(vm.card.content==null||vm.card.content.length<10){
        		document.getElementById("hiddenBorder").className ="hiddenBorder";
        		setTimeout("document.getElementById('hiddenBorder').className =''; ",1000);
        		return;
        	}
        	
        	//return;
        	vm.ue.destroy();  
            vm.isSaving = true;
            if (vm.card.id !== null) {
                Card.update(vm.card, onSaveSuccess, onSaveError);
            } else {
                Card.save(vm.card, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('milkbeeApp:cardUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

        vm.datePickerOpenStatus.createdAt = false;
        vm.datePickerOpenStatus.modifiedAt = false;

        function openCalendar (date) {
            vm.datePickerOpenStatus[date] = true;
        }
        vm.onAttachmentSelect=function($files){
        	vm.cannotpost=true;
        	vm.currentProcess=0;
        	vm.doUpload=true;
        	for (var i = 0; i < $files.length; i++) {        		
        		var fd = new FormData();
        	    fd.append("jyfile", $files[i]);     	      
      	    		$http({
        	            method: 'post',
        	            url: '/upload/attachment',
        	            data:fd,
        	            headers: {'Content-Type': undefined},
        	            transformRequest: angular.identity,
        	            uploadEventHandlers: {
        	                progress: function(e) {
        	                	if (e.lengthComputable) {
        	                		//e.loaded
        	                		vm.currentProcess = Math.round(e.loaded * 100 / (e.total*1.1));
        	                        //console.log("progress: " + vm.currentProcess + "%");
        	                        if (e.loaded == e.total) {
        	                          //console.log("File upload finished!");
        	                          //console.log("Server will perform extra work now...");
        	                        }
        	                    }
        	                }
        	            }
        	        }).success(function(ret) {
        	        	vm.cannotpost=false;
        	            if (ret.success) {     
        	            	vm.card.attachment=ret.path;
        	            	vm.currentProcess=100;
        	            }else if(!ret.success){
        	            	
        	            }
        	            
        	        }).error(function(ret) {
        	        	vm.cannotpost=false;
        	        })
        		//only one file
        		break;
        	}
        	      
        }
    }
})();
